package com.dove.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dove.entity.Menu;
import com.dove.entity.Role;
import com.dove.entity.RoleMenu;
import com.dove.mapper.RoleMapper;
import com.dove.mapper.RoleMenuMapper;
import com.dove.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dove
 * @since 2022-03-26
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuServiceImpl menuService;


    @Transactional
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
        //先删后增
        QueryWrapper<RoleMenu> qw = new QueryWrapper<>();
        qw.eq("role_id",roleId);
        roleMenuMapper.delete(qw);

        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            Menu menu = menuService.getById(menuId);
            if (menu.getPid()!=null&&!menuIdsCopy.contains(menu.getPid())) {//为二级菜单并且没有选中二级对应父级菜单
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }
    }

    @Override
    public List<Integer> findByRoleId(Integer roleId) {
        QueryWrapper<RoleMenu> qw = new QueryWrapper<>();
        qw.eq("role_id",roleId);
        List<RoleMenu> roleMenus = roleMenuMapper.selectList(qw);
        List<Integer> menuIds=new ArrayList<>();
        for (RoleMenu roleMenu : roleMenus) {
            Integer menuId = roleMenu.getMenuId();
            menuIds.add(menuId);
        }
        return menuIds;
//        return roleMenuMapper.selectByroleId(roleId);
    }
}
